package com.bs.regsystemapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.regsystemapi.entity.*;
import com.bs.regsystemapi.modal.dto.prescription.PrescriptionOrderForm;
import com.bs.regsystemapi.modal.dto.prescription.QueryPrescriptionForm;
import com.bs.regsystemapi.modal.vo.prescription.AppPatInfo;
import com.bs.regsystemapi.modal.vo.prescription.BmiInfo;
import com.bs.regsystemapi.modal.vo.prescription.PrescriptionInfo;
import com.bs.regsystemapi.modal.vo.prescription.PrescriptionListInfo;
import com.bs.regsystemapi.service.*;
import com.bs.regsystemapi.utils.ManagePageResult;
import com.bs.regsystemapi.utils.ResponseResult;
import com.bs.regsystemapi.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ning
 * @date 2023/2/6 12:13
 */
@RestController
@RequestMapping("/prescription")
@Api(tags = {"就诊单相关接口"})
@Slf4j
public class PrescriptionController {
    @Autowired
    private PrescriptionService prescriptionService;
    @Autowired
    private PrescriptionOrderService prescriptionOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private PatPersonService patPersonService;

    @ApiOperation(value = "保存就诊单")
    @PostMapping("/save")
    public ResponseResult save(@RequestBody PrescriptionInfo prescriptionInfo) {
        Map<String, Object> map = prescriptionService.save(prescriptionInfo);
        return ResponseResult.ok().put(map);
    }

    @ApiOperation(value = "完成订单")
    @PostMapping("/overOrder")
    public ResponseResult overOrder(@RequestBody PrescriptionOrder prescriptionOrder) {
        if(StringUtils.isEmpty(prescriptionOrder.getOrderNo())) {
            return ResponseResult.error("订单NO为空!");
        }
        prescriptionOrderService.endOrderStatus(prescriptionOrder);
        return ResponseResult.ok();
    }

    @ApiOperation(value = "获取就诊单列表")
    @PostMapping("/list")
    public ResponseResult getPrescriptionList(@RequestBody QueryPrescriptionForm form) {
        ManagePageResult prescriptionList = prescriptionService.getPrescriptionList(form);
        return ResponseResult.ok().put(prescriptionList);
    }

    @ApiOperation(value = "删除就诊单")
    @PostMapping("/delete")
    public ResponseResult deletePrescription(@RequestBody String prescriptionNo) {
        if(StringUtils.isEmpty(prescriptionNo)) {
            return ResponseResult.error("就诊单no不存在!");
        }
        prescriptionService.deletePrescription(prescriptionNo);
        return ResponseResult.ok();
    }

    @ApiOperation(value = "获取就诊单详情")
    @GetMapping(value = "/info")
    public ResponseResult getPrescriptionInfo(@RequestParam String prescriptionNo) {
        if(StringUtils.isEmpty(prescriptionNo)) {
            return ResponseResult.error("就诊单no不存在!");
        }
        PrescriptionListInfo prescriptionInfo = prescriptionService.getPrescriptionInfo(prescriptionNo);
        return ResponseResult.ok().put(prescriptionInfo);
    }

    @ApiOperation(value = "获取就诊单订单列表")
    @PostMapping("/orderList")
    public ResponseResult getOrderInfo(@RequestBody PrescriptionOrderForm form) {
        ManagePageResult prescriptionList = prescriptionService.getOrderInfo(form);
        return ResponseResult.ok().put(prescriptionList);
    }

    @ApiOperation(value = "删除就诊单订单")
    @PostMapping("/deleteOrder")
    public ResponseResult deleteOrder(@RequestBody String orderNo) {
        if(StringUtils.isEmpty(orderNo)) {
            return ResponseResult.error("就诊单订单no不存在!");
        }
        prescriptionService.deleteOrder(orderNo);
        return ResponseResult.ok();
    }

    @ApiOperation(value = "App获取就诊报告")
    @GetMapping("/getAppReport")
    public ResponseResult getAppReport(HttpServletRequest request) {
        String patNo = "";
        Cookie[] cookies = request.getCookies();
        if (cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("appPatient".equals(cookie.getName())){
                    patNo = cookie.getValue();
                }
            }
        }
        LambdaQueryWrapper<Prescription> lbw = new LambdaQueryWrapper<>();
        lbw.eq(Prescription::getPatNo,patNo);
        List<Prescription> list = prescriptionService.list(lbw);
        List<Prescription> dtoList = list.stream().map(item -> {
            Prescription pre = new Prescription();
            BeanUtils.copyProperties(item,pre);

            LambdaQueryWrapper<UserEntity> lbw2 = new LambdaQueryWrapper();
            lbw2.eq(UserEntity::getUserNo,item.getDoctorNo());
            UserEntity one = userService.getOne(lbw2);
            if (null != one){
                pre.setDoctorNo(one.getUserRealName());
            }

            LambdaQueryWrapper<PatientEntity> lbw3 = new LambdaQueryWrapper();
            lbw3.eq(PatientEntity::getPatNo,item.getPatNo());
            PatientEntity patientServiceOne = patientService.getOne(lbw3);
            if (null != patientServiceOne){
                pre.setPatNo(patientServiceOne.getPatRealName());
            }

            return pre;
        }).collect(Collectors.toList());
        return ResponseResult.ok().put(dtoList);
    }

    @ApiOperation(value = "App获取个人信息")
    @GetMapping("/getPat")
    public ResponseResult getPatInfo(HttpServletRequest request) {
        AppPatInfo info = new AppPatInfo();
        String patNo = "";
        Cookie[] cookies = request.getCookies();
        if (cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("appPatient".equals(cookie.getName())){
                    patNo = cookie.getValue();
                }
            }
        }
        LambdaQueryWrapper<Prescription> lbw = new LambdaQueryWrapper<>();
        lbw.eq(Prescription::getPatNo,patNo).orderByDesc(Prescription::getCreatTime);
        List<Prescription> list = prescriptionService.list(lbw);

        Prescription prescription = list.get(0);
        info.setPersonNo(prescription.getPersonNo());
        info.setPatNo(prescription.getPatNo());
        info.setHeight(prescription.getPersonHeight());
        info.setWeight(prescription.getPersonWeight());
        info.setOccupation(prescription.getPersonOccupation());
        info.setMaritalStatus(prescription.getPersonMaritalStatus());
        info.setAllHistory(prescription.getPersonAllergicHistory());
        info.setPastHistory(prescription.getPersonPastMedicalHistory());
        info.setInsuranceNo(prescription.getInsuranceNo());

        LambdaQueryWrapper<PatPerson> lbw2 = new LambdaQueryWrapper<>();
        lbw2.eq(PatPerson::getPatNo,patNo);
        PatPerson person = patPersonService.getOne(lbw2);
        if (null != person){
            info.setIdCard(person.getIdentifyCard());
            info.setPhone(person.getPersonPhone());
            info.setGender(person.getPersonGender());
        }

        LambdaQueryWrapper<PatientEntity> lbw3 = new LambdaQueryWrapper<>();
        lbw3.eq(PatientEntity::getPatNo,patNo);
        PatientEntity patient = patientService.getOne(lbw3);
        if (null != patient){
            info.setName(patient.getPatRealName());
        }

        return ResponseResult.ok().put(info);
    }

    @ApiOperation(value = "App获取BMI")
    @GetMapping("/getBMI")
    public ResponseResult getBMI(HttpServletRequest request) {
        String patNo = "";
        Cookie[] cookies = request.getCookies();
        if (cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("appPatient".equals(cookie.getName())){
                    patNo = cookie.getValue();
                }
            }
        }

        LambdaQueryWrapper<Prescription> lbw = new LambdaQueryWrapper<>();
        lbw.eq(Prescription::getPatNo,patNo).orderByDesc(Prescription::getCreatTime);
        List<Prescription> list = prescriptionService.list(lbw);
        Prescription prescription = list.get(0);

        BigDecimal h = new BigDecimal(prescription.getPersonHeight());
        BigDecimal value = new BigDecimal("100");
        BigDecimal height = h.divide(value, 2, BigDecimal.ROUND_HALF_UP);
        BigDecimal weight = new BigDecimal(prescription.getPersonWeight());

        BigDecimal multiplyHeight = height.multiply(height);

        double bmi = weight.divide(multiplyHeight, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

        BmiInfo info = new BmiInfo();
        info.setBmi(bmi);

        if (bmi<18.5){
            info.setDetail("体重过低");
        }else if(bmi>=18.5 && bmi<23){
            info.setDetail("正常范围");
        }else if (bmi>=23 && bmi<25){
            info.setDetail("肥胖前期");
        }else if(bmi>=25 && bmi<30){
            info.setDetail("I度肥胖");
        }else if (bmi>=30 && bmi<40){
            info.setDetail("II度肥胖");
        }else if(bmi >= 40.0){
            info.setDetail("III度肥胖");
        }

        LambdaQueryWrapper<PatientEntity> lbw2 = new LambdaQueryWrapper<>();
        lbw2.eq(PatientEntity::getPatNo,patNo);
        PatientEntity patient = patientService.getOne(lbw2);

        info.setName(patient.getPatRealName());
        info.setGender(patient.getPatGender());

        return ResponseResult.ok().put(info);
    }
}
